package com.project;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;

@WebServlet("/ReschedulingCancellationServlet")
public class ReschedulingCancellationServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 解析请求数据
        String jsonData = request.getParameter("requestData");
        Map<String, String> requestInfo = new Gson().fromJson(jsonData, Map.class);
        String action = request.getParameter("action");
        
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        if (admin == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        boolean result = false;
        List<String> input = new ArrayList<>();

        if ("approve".equals(action)) {
            if ("Change".equals(requestInfo.get("type"))) {
                input.add(requestInfo.get("orderId"));
                input.add(requestInfo.get("newFid"));
                input.add(requestInfo.get("newPosition"));
                input.add(requestInfo.get("userId"));
                result = admin.Process_rescheduling(input);
            } else {
                input.add(requestInfo.get("orderId"));
                input.add(requestInfo.get("userId"));
                result = admin.Process_refunds(input);
            }
        } else {
            // 拒绝操作可根据需求添加日志或其他处理
            result = true;
        }

        if (result) {
            // 从ServletContext中移除已处理的请求
            List<Map<String, String>> pendingRequests = (List<Map<String, String>>) 
                request.getServletContext().getAttribute("pendingReschedulingCancellations");
            if (pendingRequests != null) {
                pendingRequests.removeIf(req -> req.get("orderId").equals(requestInfo.get("orderId")));
                request.getServletContext().setAttribute("pendingReschedulingCancellations", pendingRequests);
            }
            response.sendRedirect("handleReschedulingCancellation.jsp?result=success");
        } else {
            response.sendRedirect("handleReschedulingCancellation.jsp?result=failure");
        }
    }
}